package pl.edu.pw.mini.gui;

import com.sun.star.comp.helper.BootstrapException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.tree.MutableTreeNode;
import pl.edu.pw.mini.adapter.IAdapterStrategy;
import pl.edu.pw.mini.adapter.documents.ZohoDocument;
import pl.edu.pw.mini.exceptions.ConnectionException;
import pl.edu.pw.mini.exceptions.InternalException;
import pl.edu.pw.mini.exceptions.InternalRuntimeException;
import pl.edu.pw.mini.exceptions.OpenOfficeException;
import pl.edu.pw.mini.oo.OOInputStream;
import pl.edu.pw.mini.adapter.OpenOfficeAdapter;
import pl.edu.pw.mini.adapter.documents.Document;
import pl.edu.pw.mini.state.StateManager;
import pl.edu.pw.mini.adapter.ZohoAdapter;
import pl.edu.pw.mini.adapter.ZohoStrategy;
import pl.edu.pw.mini.history.HistoryEntry;
import pl.edu.pw.mini.history.HistoryManager;
/*
 * ZohoFrame.java
 *
 * Created on 28 listopad 2007, 16:24
 */

/**
 * Frame that allows user to upload/download documents to Zoho server and load list of online documents
 * @author Diana
 */
public class ZohoFrame extends FunctionalFrame {
    protected Map<MutableTreeNode, Object>  workbookIndex;
    protected ZohoDocumentsTableModel currentZohoTableModel;
    protected IAdapterStrategy strategy= ZohoStrategy.getInstance();
    protected SearchZohoFrame searchZohoFrame;
    
    /** Creates new form ZohoFrame */
    public ZohoFrame() {
        initComponents();
        searchZohoFrame=new SearchZohoFrame();
        workbookIndex=GuiHelper.fillTree(treeList,new HashMap<String,Object>());
        GuiHelper.prepareMainDocumentFrame(jTable1,treeList);
        
        setNewZohoModel(new ArrayList<Document>());
        jFileChooser1.setFileFilter(new ZohoDocumentFilter());
        
    }
    private void setNewZohoModel(List<Document> data){
        List l=jTable1.getRowSorter().getSortKeys();
        currentZohoTableModel=new ZohoDocumentsTableModel(data);
        jTable1.setModel(currentZohoTableModel);
        jTable1.getRowSorter().setSortKeys(l);
        invalidate();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jFileChooser1 = new javax.swing.JFileChooser();
        jFileChooser2 = new javax.swing.JFileChooser();
        btnSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeList = new javax.swing.JTree();
        btnLoadList = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btnSearchAndSave = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnLoad = new javax.swing.JButton();
        txtDocName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabelStatus = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnUpdate = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        btnOpenInWebBrowser = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Zoho");
        addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
                formAncestorMoved(evt);
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
            }
        });

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        treeList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeListMouseClicked(evt);
            }
        });
        treeList.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                treeListValueChanged(evt);
            }
        });

        jScrollPane1.setViewportView(treeList);

        btnLoadList.setText("Load list");
        btnLoadList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadListActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Online documents list");

        btnSearchAndSave.setText("From file...");
        btnSearchAndSave.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnSearchAndSaveMousePressed(evt);
            }
        });
        btnSearchAndSave.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                btnSearchAndSaveMouseMoved(evt);
            }
        });
        btnSearchAndSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchAndSaveActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Upload document");

        btnSave.setText("Currently edited");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnLoad.setText("Load selected document");
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });

        txtDocName.setToolTipText("Hint: In order to select and upload multiple files leave this field empty. ");

        jLabel3.setText("Title");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabelStatus.setText("Status: Idle");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(741, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setText("Update document");

        btnUpdate.setText("Currently edited");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setText("Search documents");

        btnOpenInWebBrowser.setText("Open selected document in web browser");
        btnOpenInWebBrowser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenInWebBrowserActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addContainerGap(828, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addComponent(jLabel2)
                    .addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                    .addComponent(btnUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(44, 44, 44))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnLoadList, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(btnSearchAndSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(63, 63, 63)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(txtDocName, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnLoad)
                            .addComponent(btnOpenInWebBrowser))
                        .addGap(70, 70, 70))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 764, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDocName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSearchAndSave)
                            .addComponent(btnSave))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnOpenInWebBrowser)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLoadList)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOpenInWebBrowserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenInWebBrowserActionPerformed
// TODO add your handling code here:
        if (isWorkerThreadBusy()){
            return;
        }
        final String docName=txtDocName.getText();
        
        if (!checkCredWithWarning()){
            return;
        }
        Runnable run = new Runnable(){
            public void run() {
                try{
                    int[] rowSel=jTable1.getSelectedRows();
                    if (rowSel==null || rowSel.length!=1){
                        return;
                    }
                    int selected=jTable1.convertRowIndexToModel(rowSel[0]);
                    Document doc=currentZohoTableModel.getAt(selected);
                    
                    renderBusy("Status: Opening...");
                    GuiHelper.openURLInDefaultBrowser(ZohoAdapter.getAdapter().getDocumentURL((ZohoDocument)doc));
                    
                } catch (Exception ex) {
                    ex.printStackTrace();
                    GuiHelper.exceptionHandler(ex,getServiceName());
                }finally{
                    renderIdle();
                    markWorkerThreadFinished();
                }
            }
            
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnOpenInWebBrowserActionPerformed

    private void treeListValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_treeListValueChanged
        treeListMouseClicked(null);
    }//GEN-LAST:event_treeListValueChanged
    
    private void formAncestorMoved(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formAncestorMoved
// TODO add your handling code here:
    }//GEN-LAST:event_formAncestorMoved
    
    private void treeListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeListMouseClicked
        int[] selRows=treeList.getSelectionRows();
        if (selRows==null || selRows.length!=1){
            return;
        }
        MutableTreeNode selectedNode = (MutableTreeNode)treeList.getSelectionPath().getLastPathComponent();
        Object obj = workbookIndex.get(selectedNode);
        if (obj instanceof List){
            setNewZohoModel((List<Document>)obj);
        }
        
        
    }//GEN-LAST:event_treeListMouseClicked
    
    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        if (isWorkerThreadBusy()){
            return;
        }
        final String docName=txtDocName.getText();
        
        if (!checkCredWithWarning()){
            return;
        }
        Runnable run = new Runnable(){
            public void run() {
                try{
                    renderBusy("Status: Updating...");
                    if(!ZohoInterfaceLogic.getInstance().updateDocument()){
                         renderIdle();
                          return;
                    }
                    HistoryManager.addHistoryEntry(HistoryEntry.TypeOfEntry.Other, docName);
                } catch(ConnectionException ex){
                    GuiHelper.exceptionHandler(ex,getServiceName());
                }catch (InternalException ex) {
                   GuiHelper.exceptionHandler(ex,getServiceName());
                } catch (OpenOfficeException ex) {
                   GuiHelper.exceptionHandler(ex,getServiceName());
                }  catch (InternalRuntimeException ex) {
                   GuiHelper.exceptionHandler(ex,getServiceName()); 
                }
                   finally{
                    renderIdle();
                    markWorkerThreadFinished();
                }
                SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                        btnLoadListActionPerformed(null);
                    }
                    
                });
            }
            
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnUpdateActionPerformed
    
    private void btnSearchAndSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchAndSaveActionPerformed
        final String docName=txtDocName.getText();
        if (isWorkerThreadBusy()){
            return;
        }
        if (!checkCredWithWarning()){
            return;
        }
        if (docName==null || "".equals(docName)){
            jFileChooser1.setMultiSelectionEnabled(true);
        } else{
            jFileChooser1.setMultiSelectionEnabled(false);
        }
        if (jFileChooser1.showOpenDialog(this)!=JFileChooser.APPROVE_OPTION){
            return;
        }
        File selFile = null;
        File []selFiles = null;
        if (jFileChooser1.isMultiSelectionEnabled()){
            selFiles = jFileChooser1.getSelectedFiles();
        } else{
            selFile = jFileChooser1.getSelectedFile();
        }
        
        if (selFile!=null || (selFiles!=null && selFiles.length>0)){
            final File[] finalSelFiles=selFiles;
            final File finalSelFile=selFile;
            Runnable run=new Runnable(){
                public void run() {
                    try{
                        if (finalSelFile!=null){
                            renderBusy("Status: Uploading...");
                            ZohoInterfaceLogic.getInstance().uploadFile(docName, finalSelFile);
                            HistoryManager.addHistoryEntry(HistoryEntry.TypeOfEntry.UploadZoho, docName);
                        } else{
                            for (int i=0;i<finalSelFiles.length;i++){
                                renderBusy("Status: Uploading file "+(i+1)+"/"+finalSelFiles.length+"...");
                                ZohoInterfaceLogic.getInstance().uploadFile(getFileNameFromPath(finalSelFiles[i]), finalSelFiles[i]);
                                HistoryManager.addHistoryEntry(HistoryEntry.TypeOfEntry.UploadZoho, getFileNameFromPath(finalSelFiles[i]));
                                renderIdle();
                            }
                        }
                    } catch(IOException ex){
                        GuiHelper.exceptionHandler(ex,getServiceName());
                        return;
                    }catch(ConnectionException ex){
                        GuiHelper.exceptionHandler(ex,getServiceName());
                        return;
                    } finally{
                        renderIdle();
                        markWorkerThreadFinished();
                    }
                    SwingUtilities.invokeLater(new Runnable(){
                        public void run() {
                            btnLoadListActionPerformed(null);
                        }
                        
                    });
                }
            };
            runSynchIfPossible(run);
        }
    }//GEN-LAST:event_btnSearchAndSaveActionPerformed
    
    
    private String getFileNameFromPath(File file) {
        String full=file.getName();
        String ext = DocumentFilter.getExtension(file);
        String name = full.replaceAll("."+ext,"");
        return name;
    }
    private boolean checkCredWithWarning(){
        return GuiHelper.checkAdapterCredWithWarning(strategy);
    }
    
    private String getServiceName(){
        return strategy.getServiceId();
    }
    
    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (isWorkerThreadBusy()){
            return;
        }
        final String docName=txtDocName.getText();
        
        if (!checkCredWithWarning()){
            return;
        }
        Runnable run = new Runnable(){
            public void run() {
                try{
                    renderBusy("Status: Uploading...");
                    ZohoInterfaceLogic.getInstance().uploadDocument(docName);
                    HistoryManager.addHistoryEntry(HistoryEntry.TypeOfEntry.UploadZoho, docName);
                } catch(Exception ex){
                    ex.printStackTrace();
                    GuiHelper.exceptionHandler(ex,getServiceName());
                }finally{
                    renderIdle();
                    markWorkerThreadFinished();
                }
                SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                        btnLoadListActionPerformed(null);
                    }
                    
                });
            }
            
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnSaveActionPerformed
///////////////////////////////////////////////////////////////////////////////// maciek
    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        if (isWorkerThreadBusy()){
            return;
        }
        if (!checkCredWithWarning()){
            return;
        }
        Runnable run = new Runnable(){
            public void run() {
                try{
                    int[] rowSel=jTable1.getSelectedRows();
                    if (rowSel==null || rowSel.length!=1){
                        return;
                    }
                    int selected=jTable1.convertRowIndexToModel(rowSel[0]);
                    Document doc=currentZohoTableModel.getAt(selected);
                    
                    renderBusy("Status: Downloading...");
                    byte[] content=ZohoAdapter.getAdapter().getDocumentContent(StateManager.getZoho(),(ZohoDocument)doc);
                    pl.edu.pw.mini.oo.OOInputStream ooInputStream =new OOInputStream(content);
                    com.sun.star.lang.XComponent xDocComponent = OpenOfficeAdapter.showDocument(doc.getTitle(),ooInputStream);
                    OpenOfficeAdapter.storeDocumentToStateManager(xDocComponent,(ZohoDocument)doc);
                    HistoryManager.addHistoryEntry(HistoryEntry.TypeOfEntry.DownloadZoho, doc.getTitle());
                    
                }catch (ConnectionException ex) {
                    GuiHelper.exceptionHandler(ex,getServiceName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    GuiHelper.exceptionHandler(ex,getServiceName());
                }finally{
                    renderIdle();
                    markWorkerThreadFinished();
                }
            }
            
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnLoadActionPerformed
///////////////////////////////////////////////////////////////////////////////// end maciek
    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        searchZohoFrame.setVisible(true);
        searchZohoFrame.toFront();
    }//GEN-LAST:event_btnSearchActionPerformed
    
    private void btnLoadListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadListActionPerformed
        if (isWorkerThreadBusy()){
            return;
        }
        if (!checkCredWithWarning()){
            return;
        }
        Runnable run = new Runnable(){
            public void run() {
                try {
                    renderBusy("Status: Loading...");
                    final List<Document> wbList=ZohoAdapter.getAdapter().getListOfDocuments(StateManager.getZoho());
                    SwingUtilities.invokeLater(new Runnable(){
                        public void run() {
                            workbookIndex=GuiHelper.fillTree(treeList,ZohoInterfaceLogic.getInstance().getMapping(wbList));
                            setNewZohoModel(wbList);
                            treeList.setSelectionRow(0);
                            renderIdle();
                        }
                    });
                } catch (ConnectionException ex) {
                    GuiHelper.exceptionHandler(ex,getServiceName());
                    GuiHelper.fillTree(treeList,new ArrayList<Document>());
                    renderIdle();
                } catch (Exception ex){
                    GuiHelper.exceptionHandler(ex,getServiceName());
                    GuiHelper.fillTree(treeList,new ArrayList<Document>());
                    renderIdle();
                }finally{
                    markWorkerThreadFinished();
                }
                
            }
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnLoadListActionPerformed
    
    protected JLabel getStatus(){
        return jLabelStatus;
    }
    
    private void btnSearchAndSaveMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSearchAndSaveMouseMoved
// TODO add your handling code here:
    }//GEN-LAST:event_btnSearchAndSaveMouseMoved
    
    private void btnSearchAndSaveMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSearchAndSaveMousePressed
        
    }//GEN-LAST:event_btnSearchAndSaveMousePressed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnLoadList;
    private javax.swing.JButton btnOpenInWebBrowser;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnSearchAndSave;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFileChooser jFileChooser2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTree treeList;
    private javax.swing.JTextField txtDocName;
    // End of variables declaration//GEN-END:variables
    
}
